package org.gpswalker.sys.server.components;

import java.util.Calendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import org.gpswalker.sys.server.misc.Logger;

public class GPS {
    public static final double SEMIMAJOR = 6378137.0; // METERS, SEMI MAJOR AXIS
    // OF THE ELLIPSOID
    public static final double SEMIMINOR = 6356752.314245; // METERS, SEMI MINOR
    // AXIS OF THE THING
    public static final double INVERSEFLATTENING = 298.257223563; // I DON'T

    // KNOW WHAT
    // IT IS.

    public static double distFrom(double lat1, double lng1, double lat2,
	    double lng2) {
	double earthRadius = SEMIMINOR;// 3958.75;
	double dLat = Math.toRadians(lat2 - lat1);
	double dLng = Math.toRadians(lng2 - lng1);
	double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
		+ Math.cos(Math.toRadians(lat1))
		* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
		* Math.sin(dLng / 2);
	double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	double dist = earthRadius * c;

	int meterConversion = 1;

	return new Float(dist * meterConversion).floatValue();
    }

    public static Calendar parseXSD(String xsd) {
	boolean isUTC = false;
	boolean plus = false;

	// Logger.log(null, "xsd is " + xsd);

	String[] dateAndTime = xsd.split("T");
	if (xsd.endsWith("Z")) {
	    isUTC = true;
	} else {
	    plus = dateAndTime[1].contains("+");
	}

	String[] timeAndOffset = null;
	timeAndOffset = dateAndTime[1].split("\\+|-|Z");

	String[] yyyymmdd = dateAndTime[0].split("-");
	String[] hhmmss = timeAndOffset[0].split(":");

	Calendar cal = Calendar.getInstance();

	cal.set(Integer.parseInt(yyyymmdd[0]),
		Integer.parseInt(yyyymmdd[1]) - 1, Integer
			.parseInt(yyyymmdd[2]), Integer.parseInt(hhmmss[0]),
		Integer.parseInt(hhmmss[1]), Integer.parseInt(hhmmss[2]));

	if (!isUTC) {
	    String[] hoursAndMins = timeAndOffset[1].split(":");
	    int millis = ((Integer.parseInt(hoursAndMins[0]) * 60) + (Integer
		    .parseInt(hoursAndMins[1]))) * 60 * 1000;

	    if (!plus) {
		millis = millis * -1;
	    }
	    TimeZone tz = new SimpleTimeZone(millis, TimeZone
		    .getAvailableIDs(millis)[0]);

	    cal.setTimeZone(tz);
	}

	return cal;

    }

}
